//
//  NetworkTools.m
//  Test
//
//  Created by mac on 16/3/10.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "NetworkTools.h"

@protocol NetworkToolsProxy <NSObject>

@optional

- (NSURLSessionDataTask*)dataTaskWithHTTPMethod:(NSString*)method
                                      URLString:(NSString*)URLString
                                     parameters:(id)parameters
                                        success:(void (^)(NSURLSessionDataTask*, id))success
                                        failure:(void (^)(NSURLSessionDataTask*, NSError* error))failure;

@end

//AFN 内部已经实现
@interface NetworkTools () <NetworkToolsProxy>

@end

@implementation NetworkTools

+ (instancetype)sharedTools
{
    static NetworkTools* instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] initWithBaseURL:nil];
        instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];
    });
    return instance;
}

//只需要返回信号即可，不需要定义 完成回调的 block
- (RACSignal*)request:(RequestMethod)method URLString:(NSString*)URLString parameters:(id)parameters
{
    NSString* methodName = (method == GET) ? @"GET" : @"POST";

    //信号的返回值，一般是对信号销毁的处理，一般给nil即可
    return [RACSignal createSignal:^RACDisposable*(id<RACSubscriber> subscriber) {

        //调用网络方法
        [self dataTaskWithHTTPMethod:methodName URLString:URLString parameters:parameters success:^(NSURLSessionDataTask* _Nonnull task, id _Nonnull responseObject) {
            //通知订阅者消息
            [subscriber sendNext:responseObject];

            //结束订阅 后续不再发送网络通知
            [subscriber sendCompleted];
        }
            failure:^(NSURLSessionDataTask* _Nonnull task, NSError* _Nonnull error) {
                //通知订阅者出现错误
                [subscriber sendError:error];
            }];
        return nil;
    }];
}

@end
